package com.blazegame.logging;


import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import com.blazegame.logging.jdk.JdkLoggerFactory;
import com.blazegame.logging.log4j.Log4jLoggerFactory;

/**
 * 
 * @author JackChu
 * @version 1.0.0 2012-1-10 下午9:50:07
 */
public abstract class LoggerFactory {
    
    private static final ReadWriteLock lock = new ReentrantReadWriteLock();
    private static LoggerFactory factory;
    
    /**
     * 默认使用log4j,也可通过此方法来改变具体的log实现
     * @param factory
     */
    public static void setLoggerFactory(LoggerFactory factory) {
        lock.writeLock().lock();
        try {
            LoggerFactory.factory = factory;
        } finally {
            lock.writeLock().unlock();
        }
    }
    
    public static Logger getLogger(Class<?> cls) {
        return getLoggerFactory().getLoggerImpl(cls);
    }
    
    public static Logger getLogger(String name) {
    	return getLoggerFactory().getLoggerImpl(name);
    }
    
    /**
     * 默认使用log4j实现logger，如果没有log4j使用jdklog
     * @return
     */
    protected static LoggerFactory getLoggerFactory() {
        lock.readLock().lock();
        try {
            if (factory != null) {
                return factory;
            }
        } finally {
            lock.readLock().unlock();
        }
        lock.writeLock().lock();
        try {
            if (factory == null) {
                try {
                    Class.forName("org.apache.log4j.Logger");
                    factory = new Log4jLoggerFactory();
                } catch (ClassNotFoundException ex) {
                    //log4j not found, falling back to jdk logging
                    factory = new JdkLoggerFactory();
                }
            }
            return factory;
        }
        finally {
            lock.writeLock().unlock();
        }
    }
    
    protected abstract Logger getLoggerImpl(Class<?> cls);
    
    protected abstract Logger getLoggerImpl(String name); 
}
